var app = getApp(), fetchApi = require("../../../utils/httpPost.js"),
 common_Js = require("../../../component/common.js")
import Toast from '../../../component/vant/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    nick_name:'',
    isiphonex: app.globalData.isiphonex,
    isxiaomi: app.globalData.isxiaomi,
    isLoading:true,
    product_id:0,
    product:[],
    isShowPopup:false,
    productPrice:0,
    order_id:0,
    order:{},
    address:{},
    address_id:0,
    is_has_address:0,
    isVisit:0,//上需要上门的
    isAppointment:0,//开启预约的
    appointmentTime:'',
    appointmentPhone:'',
    isShowPopup:false,
    minDate: new Date().getTime(),
    remark:'',
    coupons:[],//我的抵扣券
    coupon_id:0,
    couponName:'',
    isShowPopupCoupon:false,
    couponPrice:0,
    radioCoupon:0,
    is_open_dikou:0,
    isShowPopupUserCoupon:false,
    userCoupons:[],
    userCouponName:'',
    radioUserCoupon:0,
    userCouponPrice:0,
    user_coupon_id:0,
    userVoucher:{},
    goldenMoney:0,
    useGoldenMoney:0,
    isCanUseGolden:0,
    warmName:'',
    warmIdNo:'',
    warmPhoneNum:'',// 参保人手机号
    warmAddress:'',
    warmBuyerName:'',
    warmBuyerPhone:'',//缴费人手机号
    templateIds:[],
    is_in_poly:0,
    submitState: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('paySubmit options', options)
    var order_id = parseInt(options.order_id)
    this.data.order_id = order_id;
    this.onHttpInit(order_id)
  },
  onShow:function(options){
    console.log('address', this.data.address);
    if(this.data.address!=undefined){
      this.setData({
        is_has_address: 1,
        address:  this.data.address
      })
      this.onHttpInit(this.data.order_id);
    }
  }, 
  onHttpInit: function (order_id) {
    var that = this
    fetchApi.httpPost('/product/order/detail', {
      order_id: order_id,
      address_id: that.data.address.id,
    }, function (res) {
      console.log("获取订单详情", res)
      if (res.data.code == 0) {
        that.data.coupons = res.data.data.order.coupons;
        that.data.order = res.data.data.order;
        if(res.data.data.order.orderType == 4){
          that.data.templateIds =  res.data.data.templateIds;
        }
        that.data.isAppointment = res.data.data.order.isAppointment;
        that.data.address = res.data.data.address;
        console.log('that.data.address', that.data.address)
        that.data.is_in_poly = res.data.data.order.is_in_poly;

        that.setData({ 
          is_in_poly: res.data.data.is_in_poly,
          order: res.data.data.order,
          is_has_address: res.data.data.is_has_address,
          address:res.data.data.address,
          coupons:res.data.data.order.coupons,
          couponName:res.data.data.order.couponCount == 0 ? '暂无抵扣券' : (res.data.data.order.couponId > 0 ? res.data.data.order.couponName :  '去选择>>'),
          userCouponName: res.data.data.order.userCoupons !=undefined && res.data.data.order.userCoupons.length == 0 ? '暂无优惠券' : (res.data.data.order.userCouponId > 0 ? res.data.data.order.userCouponName :  '去选择>>'),
          couponPrice: res.data.data.order.couponDikouPrice,
          userCouponPrice: res.data.data.order.userCouponPrice,
          is_open_dikou:res.data.data.is_open_dikou,
          userCoupons:res.data.data.order.userCoupons,
          userVoucher:res.data.data.userVoucher,
          useGoldenMoney:res.data.data.useGoldenMoney,
          goldenMoney:res.data.data.goldenMoney,
          isCanUseGolden:res.data.data.isCanUseGolden,
          remark:res.data.data.order.remark,
        })
      }else{
        Toast.fail(res.data.msg)
      }
      that.setData({ netWork: true, isLoading: false, })
    }, function () {
      that.setData({ netWork: false, hasData: false, isLoading: false, })
    })
  },
  showMap(e){
    var merId = e.currentTarget.dataset.merId;
    console.log('that.data.address showMap', this.data.address)
    wx.navigateTo({
      url: '/pagesMer/pages/mapPoly/index?mer_id=' + merId + '&addId= ' + this.data.address.id,
    })
  },
  pushToAddress:function(){
    wx.navigateTo({
      url: "/pages/address/index?orderType=" + this.data.order.orderType
    })
  },
  showCoupons(){
    this.setData({
      isShowPopupCoupon : !this.data.isShowPopupCoupon
    })
  },
  onChangeCoupon(){
    this.setData({
      isShowPopupCoupon: !this.data.isShowPopupCoupon
    })
  },
  onChangeUserCoupon(){
    this.setData({
      isShowPopupCoupon: !this.data.isShowPopupCoupon
    })
  },
  showUserCoupons(){
    this.setData({
      isShowPopupUserCoupon : !this.data.isShowPopupUserCoupon
    })
  },
  delInfo(e){
    console.log('delInfo',e);
    var infoId = e.currentTarget.dataset.infoid;
    var that = this;
    fetchApi.httpPost('/product/order/info/delete', {
      info_id: infoId,
    }, function (res) {
      console.log("删除详情", res)
      if (res.data.code == 0) {
        Toast.success(res.data.msg)
        setTimeout(function(){
          that.onHttpInit(that.data.order_id)
        },800)
      }else{
        Toast.fail(res.data.msg)
      }
      that.setData({ netWork: true, isLoading: false, })
    }, function () {
      that.setData({ netWork: false, hasData: false, isLoading: false, })
    })
  },
  onChangeRadioCoupon(e){
    console.log('onChangeRadioCoupon',e)
    if(e.detail == '-1'){//不使用抵扣券
      this.data.coupon_id = 0;
      this.setData({
        couponName: '去选择',
        couponPrice:0,
        isShowPopupCoupon: !this.data.isShowPopupCoupon
      })
      this.onHttpUpdateCoupon(0,0);
    }else{
      var index = parseInt(e.detail);
      console.log('this.data.coupons',this.data.coupons)
      this.data.coupon_id = this.data.coupons[index].couponId;
      var price = this.data.coupons[index].dikouPrice;
      var couponName = this.data.coupons[index].couponName;
      console.log('coupon_id',this.data.coupon_id);

      // this.data.order.payPrice = this.data.order.payPrice - price;

      this.setData({
        couponName: couponName,
        couponPrice:price,
        // order:this.data.order,
        isShowPopupCoupon: !this.data.isShowPopupCoupon
      })
      this.onHttpUpdateCoupon(this.data.coupon_id,1);
    }
  },
  onChangeRadioUserCoupon(e){
    console.log('onChangeRadioUserCoupon',e)
    if(e.detail == '-1'){//不使用抵扣券
      this.data.coupon_id = 0;
      this.setData({
        userCouponName: '去选择',
        userCouponPrice:0,
        isShowPopupUserCoupon: !this.data.isShowPopupUserCoupon
      })
      this.onHttpUpdateUserCoupon(0,0);
    }else{
      var index = parseInt(e.detail);
      console.log('this.data.userCoupons',this.data.userCoupons)
      this.data.user_coupon_id = this.data.userCoupons[index].id;
      var price = this.data.userCoupons[index].dikouPrice;
      var userCouponName = this.data.userCoupons[index].couponName;
      console.log('user_coupon_id',this.data.user_coupon_id);
      this.setData({
        userCouponName: userCouponName,
        userCouponPrice:price,
        isShowPopupUserCoupon: !this.data.isShowPopupUserCoupon
      })
      this.onHttpUpdateUserCoupon(this.data.user_coupon_id,1);
    }
  },
  onHttpUpdateCoupon: function (user_coupon_id,is_use_coupon) {
    var that = this;
    fetchApi.httpPost('/product/order/useMerCoupon', {
      is_use_coupon:is_use_coupon,
      order_id:that.data.order.id,
      user_coupon_id: user_coupon_id,
    }, function (res) {
      console.log("获取优惠券数据", res)
      if (res.data.code == 0) {
        var payPrice = res.data.data;
        that.data.order.payPrice = payPrice;
        that.setData({
          // couponPrice:payPrice,
          order:that.data.order,
        })
      }
      that.setData({ netWork: true, isLoading: false, })
    }, function () {
      that.setData({ netWork: false, hasData: false, isLoading: false, })
    })
  },
  onHttpUpdateUserCoupon: function (user_coupon_id,is_use_coupon) {
    var that = this;
    fetchApi.httpPost('/product/order/useUserCoupon', {
      is_use_coupon:is_use_coupon,
      order_id:that.data.order.id,
      user_coupon_id: user_coupon_id,
    }, function (res) {
      console.log("获取优惠券数据", res)
      if (res.data.code == 0) {
        var payPrice = res.data.data;
        that.data.order.payPrice = payPrice;
        that.setData({
          // couponPrice:payPrice,
          order:that.data.order,
        })
      }else{
        Toast.fail(res.data.msg);
      }
      that.setData({ netWork: true, isLoading: false, })
    }, function () {
      that.setData({ netWork: false, hasData: false, isLoading: false, })
    })
  },
  onChangeTime(e){
    console.log('onChangeTime',e)
    var date = new Date(e.detail);
    var time = common_Js.formatTime(date);
    console.log()
    this.setData({
      isShowPopup : false,
      appointmentTime:time
    })
  },
  onAppointmentTime(){
    this.setData({
      isShowPopup : !this.data.isShowPopup
    })
  },
  onHttpGetCouponDetail: function (user_coupon_id) {
    var that = this
    fetchApi.httpPost('/user/coupon/detail', {
      user_coupon_id: user_coupon_id,
    }, function (res) {
      console.log("获取优惠券数据", res)
      if (res.data.code == 0) {
        var coupon_type = res.data.data.coupon.couponType
        if(coupon_type == 2){//直接抵扣 按次使用的
          that.setData({
            productPrice:0
          })
        }
      }
      that.setData({ netWork: true, isLoading: false, })
    }, function () {
      that.setData({ netWork: false, hasData: false, isLoading: false, })
    })
  },
  onClickCouponList:function(){
    // this.setData({isShowPopup : true})
    wx.navigateTo({
      url: '/pages/coupon/canuse/index?product_id='+ this.data.product_id,
    })
  },
  onConfirmArea:function(res){
    console.log('onConfirmArea res',res)
    var index = res.detail.index;
    var name = res.detail.value;
    this.data.coupon_id = this.data.coupons[index].id
    this.setData({
      // isShowPopup:false,
      couponName: name
    })
  },
  msgHandle(e){
    this.data.remark = e.detail;
  },
  onCancelArea:function(){
    this.setData({
      isShowPopup:false,
    })
  },
  submitOrder:function(res) {
    var orderId = res.currentTarget.dataset.orderId;
    console.log('orderId',orderId);

    // if(this.data.order.orderType == 7 && this.data.is_in_poly == 0){
    //   Toast("您的地址未在配送范围内，不能下单");
    //   return;
    // }
    // console.log('this.data.address',this.data.address)
    if(this.data.order.orderType == 7 && (this.data.address  == undefined)){
      Toast("请填写您的收货地址");
      return;
    }

    this.data.submitState = true;
    this.setData({
      submitState: true
    })

    this.requestPay(orderId);
  },
  requestPay:function(order_id){
    var that = this;
    fetchApi.httpPost('/pay/bingge/requestPay', {
      order_id: order_id,
      remark:that.data.remark,
      isAppointment: 0,
      buyerName: that.data.warmBuyerName,
      address_id: that.data.address.id,
      subject:'购买商家服务'
    }, function (res) {
      console.log('提交订单',res)
      if (res.data.code == 0) {
        var pay_data = res.data.data;
        var wxpayinfo = JSON.parse(res.data.data)
        console.log('pay_data',pay_data)
        if(wxpayinfo.result_code == 'SUCCESS'){
          that.data.submitState = false;
          that.setData({
            submitState: false
          })
          wx.requestPayment({
            timeStamp: wxpayinfo.timeStamp,
            nonceStr: wxpayinfo.nonceStr,
            package: wxpayinfo.package,
            signType: wxpayinfo.signType,
            paySign: wxpayinfo.paySign,
            success (res) { 
              console.log('requestPayment success',res);
              if(that.data.order.orderType == 4  ){
                wx.requestSubscribeMessage({
                  tmplIds: that.data.templateIds,
                  success (res) {
                    console.log('requestSubscribeMessage',res)
                    wx.redirectTo({
                      url: '/pages/order/groupShare/index?order_id=' + order_id,
                    })
                  },fail(res){
                    wx.redirectTo({
                      url: '/pages/order/groupShare/index?order_id=' + order_id,
                    })
                  }
                })
              }else{
                wx.redirectTo({
                  url: '/pages/pay/payResult/index?order_id=' + order_id+'&type=warm',
                })
              }
            },
            fail (res) {
              console.log('requestPayment fail',res)
             }
          })
        }
      } else {
        Toast.fail(res.data.msg);
        that.setData({ isLoading: false, loading: true, netWork: true })
      }
    }, function () {
        that.setData({  isLoading: false,  loading: true,  netWork: true, }) 
    })
  },
})